﻿var _t, _c, _u, _ac, _cc, _pctry=0;

$G.pay = {
	lsCashier: 'gollie_cashier',
	lsCurrentPayment: 'gollie_currentpayment',
	currentPaymentPersistPeriod: 60,
	initialize: function () { $G.pay.initEnv();},
	initEnv: function () { _t = _c = _u = _ac = _cc = undefined; },
	finalize: function () { $G.pay.initEnv(); $G.localstorage.deleteItem($G.pay.lsCurrentPayment); },
	autoLogin: function () {
		_c = $G.localstorage.getItem(this.lsCashier);
		if (_c)	$G.localstorage.extendExpiration(this.lsCashier);
		return (_c != null);
	},

	customerId: function () {
		var c, args = window.location.search.split('=');
		if (args[0] == "?c") c = args[1];
		_u = c;
	},

	vendorLogin: function () {
		$G.pay.ajax.vendorLogin({ tokenUser: $G.pay.ui.tbVendorUserName().val(), ww: $G.pay.ui.tbVendorWW().val() }, this.vendorLoginSuccess, this.vendorLoginError);
	},

	vendorLoginSuccess: function (loggedInMsg) {
		$G.localstorage.setItem($G.pay.lsCashier, { cashierId: loggedInMsg.d.CashierId, webToken: loggedInMsg.d.WebToken }, loggedInMsg.d.CookieExpiration * 60);
		$G.pay.autoLogin();
		$G.pay.afterVendorLoggedIn();
	},

	vendorLoginError: function (result) {
		switch (result.errorCode) {
			//wrong pw
			case 4: $G.pay.ui.warn(result.errorMessage);
				break;
			default:
				$G.pay.ui.fatal(result.errorMessage);
				break;
		}
	},

	afterVendorLoggedIn: function () {
		$G.pay.ui.tbAmount().val('');
		$G.pay.ui.btnApprove().hide();

		$G.pay.ajax.initPayment({ tokenUser: _c.cashierId, token: _c.webToken, consumerId: _u }, $G.pay.initPaymentSuccess, $G.pay.initPaymentError);
	},

	initPaymentError: function (result) {
		$G.pay.ui.fatal($G.string.format($G.pay.texts.initPaymentError, result.errorMessage));
	},

	initPaymentSuccess: function (paymentInfo) {
		$G.pay.ui.setPaymentInfo(paymentInfo.d);
		_t = paymentInfo.d.TransactionTicket;
		var pip = $G.pay.getPaymentInProgress();
		if (pip) 
			$G.pay.prePayCheckOk(pip.amount, pip.credit);
		else
			$G.changePage("#pnlInitial");
	},

	prePayCheck: function () {
		var amountInCents;

		if (_ac != undefined) {
			$G.pay.ui.disableCheck();
			$G.pay.ui.error($G.pay.texts.multipleCheckError);
			return;
		}

		try {
			amountInCents = $G.money.toCents(($G.pay.ui.isPayBack() ? '-' : '') + $G.pay.ui.tbEuros().val().trim() + $G.money.defaults.decimal_separator + $G.pay.ui.tbCents().val().trim());
		}
		catch (err) {
			amountInCents = undefined;
		}

		if (amountInCents == undefined || amountInCents == 0 || isNaN(amountInCents)) {
			$G.pay.ui.warn($G.pay.texts.invalidAmount);
			return;
		}

		var credit = $G.pay.ui.lblCredit().text().substring(1).trim();
		var creditInCents = $G.money.toCents(credit);
		if (creditInCents < amountInCents) {
			var dif = amountInCents - creditInCents;
			var strDif = $G.money.toMoney(dif / 100);
			$G.pay.ui.info($G.string.format($G.pay.texts.creditLow, credit, strDif));

			return;
		}

		if (amountInCents < 0) {
			var t = $G.string.format($G.pay.texts.confirmPayBack, $G.money.toMoney(-amountInCents / 100), $G.pay.ui.lblCustomerName().text());
			$G.pay.ui.confirm(t, function () { $G.pay.prePayCheckOk(amountInCents, creditInCents); });
		}
		else
			$G.pay.prePayCheckOk(amountInCents, creditInCents);
	},

	prePayCheckOk: function (amountInCents, creditInCents) {
		$G.pay.ui.lblConfirmAmount().text($G.money.toMoney(Math.abs(amountInCents / 100)));

		_ac = amountInCents; _cc = creditInCents;

		//save the payment details for a minute. Use that to prevent a customer from altering the amount if he refreshes or re-opens the page.
		$G.localstorage.setItem($G.pay.lsCurrentPayment, { customer: _u, amount: _ac, credit: _cc }, $G.pay.currentPaymentPersistPeriod);

		$G.changePage("#pnlConfirm");
	},

	getPaymentInProgress: function () {
		var pip = $G.localstorage.getItem($G.pay.lsCurrentPayment);
		if (pip) {
			if (pip.customer === _u) {
				return pip;
			}
		}
		return null;
	},

	approve: function () {
		var em = $G.pay.ui.cbEmail().prop('checked') ? '1' : '0';
		$G.pay.ui.lblGotMail().toggle(em === '1');
		$G.pay.ajax.pay({ tokenUser: _c.cashierId, token: _c.webToken, ticket: _t, suserId: _u, samount: _ac, scredit: _cc, pw: $G.pay.ui._hp, email: em }, $G.pay.paySuccess, $G.pay.payError);
	},

	paySuccess: function () {
		$G.pay.finalize();
		$G.changePage("#pnlSucceeded");
	},

	payError: function (result) {
		switch (result.errorCode) {
			/*wrong pincode*/
			case 7: _pctry++;
				if (_pctry < 3) {
					var _pctriesleft = 3 - _pctry;
					var warn = $G.string.format("{#0}<br><br>{#1}", result.errorMessage, _pctriesleft == 1 ? $G.pay.texts.finalPinAttempt : $G.string.format($G.pay.texts.attemptsLeft, _pctriesleft));
					$G.pay.ui.error(warn);
					$G.pay.ui.clearPin();
				}
				else {
					$G.pay.ui.fatal($G.pay.texts.tooManyPinTries);
				}
				break;

				/*geen bedrag ingevuld*/
			case 11: $G.pay.ui.error(result.errorMessage);
				$G.changePage("#pnlInitial");
				break;

				/*3,12: not enough credit, 6: no refund possible (no active offers), 10: transaction expired*/
			default:
				$G.pay.ui.fatal(result.errorMessage);
				break;
		}
	}
}
$G.$ = function () {
	$G.pay.initialize();
	$G.pay.ui.initialize();
	$G.pay.ajax.initialize(function () { $G.pay.ui.loader(true) }, function () { $G.pay.ui.loader(false) });
	$G.pay.customerId();
	if (_u == undefined || _u.length == 0) {
		$G.clearScreen();
		$G.pay.ui.error($G.string.format($G.pay.texts.wrongUrl, window.location.search));
	}
	else {
		if (!$G.pay.autoLogin()) { $G.changePage("#pnlVendorLogin"); }
		else $G.pay.afterVendorLoggedIn();
	}
}